package com.cloud.service.city.impl;

import com.cloud.dao.city.CityDao;
import com.cloud.model.entity.city.City;
import com.cloud.model.view.city.CityView;
import com.cloud.service.city.CityService;
import com.cloud.commons.utils.CloudCopyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
* <b><code>CityImpl</code></b>
* <p/>
* City的具体实现
* <p/>
* <b>Creation Time:</b> 2019-10-16 14:30:33.
*
* @author ${model.author}
* @version 1.0.0
* @since cloud-spring-boot-be 1.0.0
*/
@Service
public class CityServiceImpl implements CityService {

    /**
     * The Constant LOG.
     */
    private static final Logger LOG = LoggerFactory
            .getLogger(CityServiceImpl.class);

    @Autowired
    private CityDao cityDao;

    @Override
    public CityView getEntity(long id) {
        // 获取Entity
        City city = cityDao.findById(id).orElseThrow(() -> new RuntimeException("获取不到id为：" + id + "的数据记录"));
        // 复制Dao层属性到view属性
        CityView cityView = new CityView();
        CloudCopyUtils.copyBean(city, cityView);
        return cityView;
    }

    @Override
    public long getEntitiesCount() {
        return cityDao.count();
    }

    @Override
    public List<CityView> findAll() {
        List<CityView> cityViews = new ArrayList<>();
        List<City> citys = cityDao.findAll();
        for (City city : citys){
            CityView cityView = new CityView();
            CloudCopyUtils.copyBean(city, cityView);
            cityViews.add(cityView);
        }
        return cityViews;
    }

    @Override
    public CityView saveEntity(CityView cityView)  {
        // 保存的业务逻辑
        City city = new City();
        CloudCopyUtils.copyBean(cityView, city);
        // user数据库映射传给dao进行存储
        city.setCreateTime(System.currentTimeMillis());
        city.setUpdateTime(System.currentTimeMillis());
        city.setWeight(System.currentTimeMillis());
        city.setEnabled(1);
        cityDao.save(city);
        CloudCopyUtils.copyBean(city,cityView);
        return cityView;
    }

    @Override
    public void deleteEntity(long id) {
        City city = cityDao.findById(id).orElseThrow(() -> new RuntimeException("获取不到id为：" + id + "的数据记录"));
        city.setId(id);
        cityDao.delete(city);
    }

    @Override
    @Transactional(rollbackOn = { Exception.class })
    public void deleteEntities(String ids) {
        String[] entityIds= ids.split("\\,");
        List<City> citys = new ArrayList<>();
        for(String entityId : entityIds){
            City city = new City();
            city.setId(Long.valueOf(entityId));
            citys.add(city);
        }
        cityDao.deleteInBatch(citys);
    }

    @Override
    public void updateEntity(CityView cityView) {
        Specification<City> citySpecification = Optional.ofNullable(cityView).map( s -> {
            return new Specification<City>() {
                @Override
                public Predicate toPredicate(Root<City> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicates = new ArrayList<>();
                    // id
                    predicates.add(criteriaBuilder.equal(root.get("id").as(Long.class), s.getId()));

                    criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                    return criteriaQuery.getRestriction();
                }
            };
        }).orElseThrow(()->new IllegalArgumentException("CityView is null"));


        // 获取原有的属性，把不变的属性覆盖
        Optional<City> cityOptionalBySearch = cityDao.findOne(citySpecification);
        cityOptionalBySearch.map(cityBySearch -> {
            CloudCopyUtils.copyBeanExcludeNull(cityView,cityBySearch);
            cityBySearch.setUpdateTime(System.currentTimeMillis());
            cityDao.save(cityBySearch);
            return "";
        }).orElseThrow(()->new RuntimeException("无法找到id为" + cityView.getId() + "的数据记录"));
    }
}
